<template>
  <Row>
    <Col span="16" offset="4"
      ><div class="WriteBlog">
        <!-- <Input v-model="createArticleParams.title" placeholder="请输入标题">
          <span slot="prepend"> 标题 </span></Input
        > -->
        <div class="WriteBlogInput">
          <Icon type="md-create" size="24" /><input
            v-model="createArticleParams.title"
            placeholder="请输入标题"
          />
        </div>

        <mavon-editor
          v-model="createArticleParams.body"
          ref="md"
          @imgAdd="$ImgAdd"
          @imgDel="$ImgDel"
          codeStyle="vs2015"
          class="editor"
        />
        <Select
          v-model="createArticleParams.articleTypeId"
          placeholder="请选择分类"
          @on-ok="SubmitCreateType"
          @on-select="ArticleTypeSelectHandler"
          filterable
          :clearable="true"
          ref="articleTypeSelect"
          class="articleTypeSelect"
        >
          <Option
            v-for="item in articleTypeList"
            :value="item.id"
            :key="'type-' + item.id"
            >{{ item.name
            }}<Icon
              type="md-close"
              @click="DeleteTypeModal"
              size="16px"
              color="#390c5d"
          /></Option>
          <Option :value="0" :key="0">添加分类</Option>
        </Select>
        <Select
          v-model="createArticleParams.tagIds"
          style="width:300px"
          @on-select="TagSelectHandler"
          @on-create="TagCreate"
          placement="bottom"
          placeholder="请选择标签"
          filterable
          clearable
          multiple
          allow-create
          ref="tagSelect"
          class="tagDropdown"
        >
          <Option v-for="tag in tagList" :value="tag.id" :key="'tag-' + tag.id"
            >{{ tag.name
            }}<Icon
              type="md-close"
              @click="DeleteTagModal"
              size="16px"
              color="#390c5d"
              style="margin-right:16px"
          /></Option>
        </Select>
        <div class="bolgSubmit">
          <Button type="primary" @click="submit" size="large">保存</Button>
        </div>
        <!-- <Modal
          v-model="showCreateTag"
          title="新建标签"
          ok-text="创建"
          @on-ok="SubmitTagCreate"
          @on-visible-change="CreateTagVisibleChange"
          :loading="loading"
        >
          <Form
            ref="formCustom"
            :model="createTagParams"
            :rules="createTagRule"
            :label-width="100"
          >
            <FormItem label="名称" prop="name">
              <Input
                type="text"
                v-model="createTagParams.name"
                style="width: 200px"
              ></Input>
            </FormItem>
            <FormItem label="类型" prop="type">
              <Select
                v-model="createTagParams.type"
                style="width:200px"
                @on-ok="SubmitCreateType"
                @on-select="ArticleTypeSelectHandler"
                filterable
                :clearable="true"
              >
                <Option
                  v-for="item in articleTypeList"
                  :value="item.id"
                  :key="'type-' + item.id"
                  >{{ item.name
                  }}<Icon
                    type="md-close"
                    @click="DeleteTypeModal"
                    size="16px"
                    color="#390c5d"
                /></Option>
                <Option :value="0" :key="0">添加类型</Option>
              </Select>
            </FormItem>
          </Form>
        </Modal> -->
        <Modal
          v-model="showTypeModal"
          title="新建分类"
          :loading="true"
          ok-text="创建"
          @on-ok="SubmitCreateType"
          @on-cancel="CancleCreateType"
        >
          <Form
            ref="createTypeForm"
            :model="createTypeParams"
            :label-width="100"
          >
            <FormItem label="名称" prop="name">
              <Input
                type="text"
                v-model="createTypeParams.name"
                style="width: 200px"
              ></Input>
            </FormItem>
            <FormItem label="所属目录" prop="meun">
              <Select
                v-model="createTypeParams.meun"
                placeholder="请选择所属目录"
                filterable
                :clearable="true"
                style="width: 200px"
              >
                <Option
                  v-for="meun in meunList"
                  :value="meun.value"
                  :key="'meun-' + meun.value"
                  >{{ meun.name }}</Option
                >
              </Select>
            </FormItem>
            <FormItem lable="图标" prop="image">
              <Upload :before-upload="UploadArticleTypeImg" action="">
                <Button icon="ios-cloud-upload-outline">图标</Button>
              </Upload>
              <div v-if="createTypeParams.image !== null">
                Upload file: {{ createTypeParams.image.name }}
              </div>
            </FormItem>
          </Form>
        </Modal>
      </div>
    </Col>
  </Row>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
  // 注册
  components: {
    mavonEditor
  },
  data() {
    return {
      createArticleParams: {
        title: '',
        body: '',
        digest: '',
        tagIds: [],
        articleTypeId: null
      },
      activeType: 0,
      articleTypeList: [],
      tagList: [],
      showCreateTag: false,
      createTagParams: {
        name: '',
        image: null,
        type: null
      },
      meunList: [
        {
          name: '技术',
          value: 0
        },
        {
          name: '音乐',
          value: 1
        },
        {
          name: '资源分享',
          value: 2
        }
      ],
      selectTag: null,
      selectType: null,
      createTagRule: {},
      showTypeModal: false,
      createTypeParams: {
        name: '',
        image: null,
        id: 0,
        meun: null
      },
      loading: true
    }
  },
  created() {
    if (this.$route.query.id) {
      this.$api.Article.GetArticle({ id: this.$route.query.id }).then(res => {
        this.createArticleParams = {
          title: res.data.title,
          body: res.data.content,
          digest: '',
          tagIds: res.data.tagIds,
          articleTypeId: res.data.articleTypeId
        }
      })
    }
  },
  watch: {
    '$store.getters.articleTypeList': {
      handler: function(value) {
        this.articleTypeList = value
      },
      deep: true,
      immediate: true
    },
    '$store.getters.tagList': {
      handler: function(value) {
        this.tagList = value
      },
      deep: true,
      immediate: true
    }
  },
  computed: {},
  mounted() {},
  methods: {
    // 将图片上传到服务器，返回地址替换到md中
    $ImgAdd(pos, $file) {
      let formdata = new FormData()
      formdata.append('image', $file)
      this.$api.Article.UpLoadArticleImage(formdata).then(res => {
        this.$refs.md.$img2Url(pos, this.$config.serverUrl + res.data)
      })
    },
    $ImgDel(filename) {
      this.$api.Article.DeleteArticleImage({ imageName: filename[0] })
    },
    TagCreate(value) {
      this.$api.Tag.CreateTag({ name: value })
        .then(res => {
          this.$store.commit('AddToTagDic', res.data)
          this.createArticleParams.tagIds.push(res.data.id)
          console.log(this.$refs.tagSelect)
        })
        .catch(err => {
          console.log(this.$refs.tagSelect)
        })
    },
    SubmitTagCreate() {
      let formData = new FormData()
      for (const key in this.createTagParams) {
        formData.append(key, this.createTagParams[key])
      }
      this.$api.Tag.CreateTag(formData)
        .then(res => {
          this.$store.commit('AddTagToArticleTypeDic', res.data)
          this.articleTypeList = this.$store.getters.articleTypeList
          this.createArticleParams.tagIds.push(res.data.id)
          this.showCreateTag = false
          this.createTagParams = {}
        })
        .catch(err => {
          this.showCreateTag = false
        })
    },
    // 提交
    submit() {
      this.createArticleParams.digest = this.$marked(
        this.createArticleParams.body
      )
        .substr(0, 100)
        .replace(/<.*?>/g, '')
        .substr(0, 20)
      if (this.$route.query.id) {
        this.createArticleParams.id = this.$route.query.id
        this.$api.Article.UpdateArticle(this.createArticleParams).then(res => {
          this.$router.push({
            name: 'Article',
            params: {
              id: this.createArticleParams.id
            }
          })
        })
      } else {
        this.$api.Article.CreateArticle(this.createArticleParams).then(res => {
          this.createArticleParams = {}
        })
      }
    },
    TagSelectHandler(res) {
      this.selectTag = res.value
      if (res.value == '0') {
        this.CloseSelect()
        // this.$refs.tagSelect.setQuery(null)
        this.showCreateTag = true
      }
    },
    ArticleTypeSelectHandler(res) {
      this.selectType = res.value
      if (res.value == '0') {
        this.showTypeModal = true
        this.$refs.articleTypeSelect.setQuery(null)
        this.$refs.createTypeForm.resetFields()
      }
    },
    CreateTagVisibleChange() {
      if (this.showCreateTag) {
        var tags = this.createArticleParams.tagIds
        tags.splice(tags.indexOf(0), 1)
      }
    },
    CloseSelect() {
      console.log(this.$refs.tagSelect)

      this.$refs.tagSelect.visible = false
    },
    CancleCreateType() {
      this.createArticleParams.articleTypeId = null
    },
    UploadTagImg(file) {
      this.createTagParams.image = file
      return false
    },
    UploadArticleTypeImg(file) {
      this.createTypeParams.image = file
      return false
    },
    DeleteTagModal() {
      this.CloseSelect()
      this.$Modal.confirm({
        title: '删除标签',
        content: '是否删除该标签',
        onOk: () => {
          this.$api.Tag.DeleteTag({ id: this.selectTag }).then(res => {
            this.$store.commit('DeleteTag', this.selectTag)
          })
        },
        onCancel: () => {
          this.$Message.info('取消删除！')
        }
      })
      setTimeout(() => {
        var tags = this.createArticleParams.tagIds
        if (tags.indexOf(this.selectTag) !== -1) {
          tags.splice(tags.indexOf(this.selectTag), 1)
        }
      }, 10)
    },
    DeleteTypeModal() {
      this.$Modal.confirm({
        title: '删除类型',
        content: '是否删除该类型',
        onOk: () => {
          console.log(this.createTagParams.type)

          this.$api.ArticleType.DeleteArticleType({ id: this.selectType }).then(
            res => {
              this.$store.commit('DeleteArticleType', this.selectType)
            }
          )
        },
        onCancel: () => {
          this.$Message.info('取消删除！')
        }
      })
      setTimeout(() => {
        this.createTagParams.type = null
      }, 10)
    },
    SubmitCreateType() {
      let formData = new FormData()
      for (const key in this.createTypeParams) {
        formData.append(key, this.createTypeParams[key])
      }
      this.$api.ArticleType.CreateArticleType(formData)
        .then(res => {
          this.$store.commit('AddToArticleTypeDic', res.data)
          this.showTypeModal = false
          this.createArticleParams.articleTypeId = res.data.id
        })
        .catch(err => {
          this.showTypeModal = false
        })
    }
  }
}
</script>

<style lang="scss">
.bolgSubmit {
  margin-top: 10px;
}

.editor {
  margin: 10px 0;
  height: 600px;
  z-index: 2 !important;
}

.ivu-select-item i {
  float: right;
}
.WriteBlog {
  margin-top: 80px;
}
.articleTypeSelect {
  width: 200px;
  display: block;
  margin-bottom: 10px;
}
.tagDropdown {
  .ivu-icon-ios-close {
    margin-top: 2px;
  }
  .ivu-select-item i {
    margin-top: 5px;
  }
  .ivu-select-item-selected:after {
    margin-top: 5px;
  }
}
.WriteBlogInput {
  background-color: white;
  display: flex;
  border: transparent;
  border-radius: 4px;
  align-items: center;
  input {
    margin-left: 5px;
    width: 100%;
    height: 36px;
    border: none;
    border-radius: 4px;
    font-weight: 550;
    font-size: 18px;
  }
  input:focus {
    outline: none;
  }
  i {
    margin-top: 5px;
  }
}
</style>
